from time import sleep
from peewee import Model, DateTimeField, SmallIntegerField
from playhouse.pool import PooledMySQLDatabase
from core import db_config

# 两个数据库
# 优禾数据库
uho_database = PooledMySQLDatabase(database=db_config.db_name, user=db_config.db_user,
                                   password=db_config.db_password, host=db_config.db_host, port=db_config.db_port,
                                   charset="UTF8mb4", max_connections=100, stale_timeout=300)

# 康腾期货数据源相关的任何代码都不允许更改！
kt_database = PooledMySQLDatabase(database=db_config.kt_database, user=db_config.kt_user,
                                  password=db_config.kt_password, host=db_config.kt_host,
                                  charset="UTF8mb4", max_connections=100, stale_timeout=300)


class KtModel(Model):
    """
    这个模块禁止更改
    """

    class Meta:
        database = kt_database


class BaseModel(Model):
    """
    所有数据库模型需要继承的基类
    数据库所有表都要有这三个字段
    """
    is_deleted = SmallIntegerField()
    created_at = DateTimeField()
    updated_at = DateTimeField()

    class Meta:
        database = uho_database


def db_ping():
    """防止数据库连接断开"""
    uho_connection = uho_database.connection()
    kt_connection = kt_database.connection()
    try:
        uho_connection.ping(True)
        kt_connection.ping(True)
    except:
        sleep(3)
        uho_connection.ping(True)
        kt_connection.ping(True)
